
package org.utn.edu.tsb.parser_xml.Interface;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FontMetrics;
import javax.swing.ImageIcon;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import org.utn.edu.tsb.parser_xml.parser.NodeXML;

/**
 *
 * @author Marcelo
 */
public class CustomIconRenderer extends DefaultTreeCellRenderer {

    ImageIcon rootIcon, nodeIcon, nodeSelIcon, attributeIcon, attributeSelIcon;

    public CustomIconRenderer() {
        rootIcon = new ImageIcon(CustomIconRenderer.class.getResource("/images/tree/xml.png"));
        nodeIcon = new ImageIcon(CustomIconRenderer.class.getResource("/images/tree/node.png"));
        nodeSelIcon = new ImageIcon(CustomIconRenderer.class.getResource("/images/tree/node_selected.png"));
        attributeIcon = new ImageIcon(CustomIconRenderer.class.getResource("/images/tree/attribute.png"));
        attributeSelIcon = new ImageIcon(CustomIconRenderer.class.getResource("/images/tree/attribute_selected.png"));
    }

    @Override
    public Component getTreeCellRendererComponent(JTree tree,
            Object value, boolean sel, boolean expanded, boolean leaf,
            int row, boolean hasFocus) {

        super.getTreeCellRendererComponent(tree, value, sel,
                expanded, leaf, row, hasFocus);

        try{
            NodeXML nodeObj = (NodeXML)(((DefaultMutableTreeNode) value).getUserObject());
            // check whatever you need to on the node user object
            String text = nodeObj.getName();
            if (nodeObj.getValue() != null)
                text += ": \""+nodeObj.getValue()+"\"";
            setText(text);
            if (nodeObj.getProperties() != null)
                setToolTipText("Attributes: " + nodeObj.getProperties().size());
        } catch (ClassCastException e){}

        if(row == 0) setIcon(rootIcon);
        else if (!leaf) {
            setIcon(nodeIcon);
            if (sel) setIcon(nodeSelIcon);
        }
        else {
            setIcon(attributeIcon);
            if (sel) setIcon(attributeSelIcon);
        }
        

        return this;
    }

    @Override
    public Dimension getPreferredSize() {
        Dimension dim = super.getPreferredSize();
        FontMetrics fm = getFontMetrics(getFont());
        char[] chars = getText().toCharArray();

        int w = getIconTextGap() + 16;
        for (char ch : chars)  {
                w += fm.charWidth(ch);
        }
        w += getText().length();
        dim.width = w;
        return dim;
    }
}
